package de.gwtprime.server;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;

import de.gwtprime.server.Singleton.UpdatableSingleton;
import de.gwtprime.server.sql.helper.HibernateHelper;

public class Config {

	private Entity config;
	
	boolean useDatastore;
	
	public enum Param{
		
		AppUrl("appUrl", "www.litecoin-boerse.de"),
		rpcIP("rpcIP", "54.245.190.123"),
		rpcPort("rpcPort", "9332"),
		tradingFee("tradingFee", "1"); // Trading fee in percent
		
		Param(String key, String defaultVal){
			this.key = key;
			this.defaultVal = defaultVal;
		}

		private String key;
		private String defaultVal;
		
		public String getKey() {
			return key;
		}

		public String getDefaultVal() {
			return defaultVal;
		}
	}
	
	private Config(boolean useDatastore){
		
		this.useDatastore = useDatastore;
		if(!useDatastore){
			return;
		}
		
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

		try {
			config =  datastore.get(new Entity("Config", "config").getKey());
		} catch (Exception e1) {
			config = new Entity("Config", "config");
		}
		
		datastore.put(config);
		
	}
	
	private static UpdatableSingleton<Config> instance = new UpdatableSingleton<Config>(){
		protected Config createInstance() throws Exception
		{
			return new Config(!HibernateHelper.test);
		}
	};
	
	public static Config getInstance(){
		return instance.instance();
	}
	
	public String getProperty(String key){
		return config.getProperty(key).toString();
	}
	
	public Double getPropertyAsDouble(Param param){
		return Double.parseDouble(getProperty(param));
	}
	
	public String getProperty(Param param){
		if(!useDatastore) return param.getDefaultVal();
		
		String val = (String) config.getProperty(param.getKey());
		
		if(val!=null) return val;
		
		return param.getDefaultVal();
	}
}
